﻿#include "character.h"
#include "../config.h"
#include "../utility.h"
#include "map.h"
#include <algorithm>
using namespace std;

#ifndef NDEBUG
#	include "character.inl"
#endif

int const Character::s_iMoveFrame[MOVE_FRAMES] = { 0, 1, 0, 2 }; // 站立, 迈左腿, 站立, 迈右腿
int const Character::s_iMoveSpeed = 4;

Character::Character(int x, int y)
: m_eDirection(DOWN), m_iFrame(0)
, m_x(x), m_y(y), m_dx(0), m_dy(0)
{

}

void Character::Update(Map const& kMap)
{
	this->m_x = max(0, min((kMap.GetXCount() - 1) * Map::CX_TILE, this->m_x + this->m_dx));
	this->m_y = max(0, min((kMap.GetYCount() - 1) * Map::CY_TILE, this->m_y + this->m_dy));

	// 有运动时播放动画, 否则为静止状态
	this->m_iFrame = (this->m_dx != 0 || this->m_dy != 0) ? this->m_iFrame + 1 : 0;

	// 根据运动方向设置朝向
	if		(this->m_dx > 0)	this->m_eDirection = RIGHT;
	else if (this->m_dx < 0)	this->m_eDirection = LEFT;
	if		(this->m_dy > 0)	this->m_eDirection = DOWN;
	else if (this->m_dy < 0)	this->m_eDirection = UP;
}

void Character::Render(Image& image, int mapX, int mapY)
{
	image.SetFrame(static_cast<int>(this->m_eDirection) * 3 + s_iMoveFrame[this->m_iFrame / 4 % MOVE_FRAMES]);
	image.Render(static_cast<float>(m_x - mapX), static_cast<float>(m_y - 16 - mapY)); // 人物超出半个格子
}

bool Character::IsInFrontOf(Character const& other)
{
	static int const xOffset[4] = { 0, -1, 0, 1 };
	static int const yOffset[4] = { 1, 0, -1, 0 };

	int x = other.m_x + Map::CX_TILE * xOffset[other.m_eDirection];
	int y = other.m_y + Map::CY_TILE * yOffset[other.m_eDirection];

	return (m_x == x) && (m_y == y);
}

void Character::FaceTo(Character const& other)
{
	if (m_x < other.m_x)		this->m_eDirection = RIGHT;
	else if (m_x > other.m_x)	this->m_eDirection = LEFT;

	if (m_y < other.m_y)		this->m_eDirection = DOWN;
	else if (m_y > other.m_y)	this->m_eDirection = UP;
}